package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ljj
 * @create 2022-11-16-15:07
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    /**
     * 新增菜品，同时新增口味数据
     * @param dishDto
     */
    @Transactional
    @Override
    public void saveWithFloavor(DishDto dishDto) {
        //
        this.save(dishDto);
        //保存菜品口味数据到口味表
        Long id = dishDto.getId();
        dishDto.getFlavors().forEach(a->a.setDishId(id));
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    public List<DishDto> getDishInfo(String name) {
        return baseMapper.getDishInfo(name);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        return baseMapper.getByIdWithFlavor( id);
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //DishServiceImpl proxy = (DishServiceImpl) AopContext.currentProxy();
        dishService.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(a-> a.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    public List<DishDto> getDishDtoInfoByDish(Dish dish) {
        return baseMapper.getDishDtoInfoByDish(dish);
    }
}
